package vip.wangwenhao.sso.controller;

import org.apache.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import vip.wangwenhao.common.enums.ResultCode;
import vip.wangwenhao.common.enums.RoleEnum;
import vip.wangwenhao.common.result.Result;
import vip.wangwenhao.common.util.HttpUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangwenhao
 */
@Controller
public class PageController {

    @GetMapping(value = "/")
    public void defaultPath(HttpServletResponse response, Authentication authentication) {
        try {
            boolean isAdmin = authentication.getAuthorities().stream().anyMatch(authority -> RoleEnum.admin.name().equals(((GrantedAuthority) authority).getAuthority()));
            if (isAdmin) {
                response.sendRedirect("/index");
            } else {
                response.sendRedirect("/home");
            }
        } catch (IOException e) {
            HttpUtils.response(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, Result.fail(ResultCode.ERROR_SERVER_FAILED, e.getMessage()));
        }
        return;
    }

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }
}